package com.linkoog.devtools.code_generator.action.code;

import com.intellij.openapi.roots.ProjectRootManager;
import com.linkoog.devtools.code_generator.wizard.generate.database.template.TemplateSelectConfigStep;
import com.linkoog.devtools.intellij.wizard.WizardStep;
import com.linkoog.devtools.intellij.wizard.WizardDialog;
import com.linkoog.devtools.code_generator.wizard.generate.ddl.DDLSqlConfigStep;
import com.linkoog.devtools.code_generator.wizard.generate.ddl.TableInfoConfigStep;
import com.linkoog.devtools.code_generator.wizard.GenerateWizardContext;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiManager;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

public class DDLSqlCodeCreaterAction extends AnAction implements DumbAware {

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        Project project = event.getProject();
        if (project == null){
            return;
        }

        Module module = event.getData(LangDataKeys.MODULE);
        if (module == null){
            return;
        }

        VirtualFile selectedPackageVF = event.getData(LangDataKeys.VIRTUAL_FILE);
        if (selectedPackageVF == null || !selectedPackageVF.isDirectory()) return;

        if ("controller".equals(selectedPackageVF.getName())){
            selectedPackageVF = selectedPackageVF.getParent();
        }

        String selectedPackageName = ProjectRootManager.getInstance(project).getFileIndex().getPackageNameByDirectory(selectedPackageVF);
        if (StringUtils.isBlank(selectedPackageName)) {
            selectedPackageName = "<default>";
        }

        PsiDirectory basePsiDirectory = PsiManager.getInstance(project).findDirectory(selectedPackageVF);
        if (basePsiDirectory == null){
            return;
        }

        GenerateWizardContext wizardContext = new GenerateWizardContext();
        wizardContext.setProject(project);
        wizardContext.setModule(module);
        wizardContext.setSelectedPackageVF(selectedPackageVF);
        wizardContext.setSelectedPackage(selectedPackageName);
        wizardContext.setBasePsiDirectory(basePsiDirectory);

        WizardDialog wizardDialog = new WizardDialog(project, wizardContext,"Generate Code from DDL", new WizardStep[]{
                new DDLSqlConfigStep(project,wizardContext),
                new TableInfoConfigStep(project,wizardContext),
                new TemplateSelectConfigStep(project,wizardContext),
        });
        if (wizardDialog != null && !wizardDialog.showAndGet()){
            return;
        }
    }
}
